package com.web.utils;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

public class FileUtil {
	/**
	 * 
	 * @param path        文件最终保存路劲
	 * @param file        原始文件
	 * @param desFileName 最终保存文件名称
	 * @return
	 */
	public static boolean Save(String path, MultipartFile file, String desFileName) {
		File filePath = new File(path);
		if (!filePath.exists()) {
			filePath.mkdirs();
		}
		File dest = new File(desFileName);
		try {
			// 保存文件;
			file.transferTo(new File(path + dest));
			return true;
		} catch (IOException e) {
			// LOGGER.error(e.toString(), e);
			return false;
		}
	}

	public static ResponseEntity<byte[]> download(HttpServletRequest request, String absPath) throws IOException {
		String tPath = System.getProperties().getProperty("user.home") + absPath;
		System.out.println("文件路径应该为:" + tPath);
		File file = new File(tPath);
		if (file.exists()) {
			byte[] body = null;
			InputStream is = new FileInputStream(file);
			body = new byte[is.available()];
			is.read(body);
			HttpHeaders headers = new HttpHeaders();
			headers.add("Content-Disposition", "attchement;filename=" + file.getName());
			HttpStatus statusCode = HttpStatus.OK;
			ResponseEntity<byte[]> entity = new ResponseEntity<>(body, headers, statusCode);
			return entity;
		} else {
			HttpHeaders headers = new HttpHeaders();
			headers.add("Content-Disposition", "attchement;filename='不存在'");
			HttpStatus statusCode = HttpStatus.OK;
			ResponseEntity<byte[]> entity = new ResponseEntity<>(null, headers, statusCode);
			return entity;
		}
	}

	public static boolean SaveImgIcon(String path, MultipartFile file, String desFileName) {
		File filePath = new File(path);
		if (!filePath.exists()) {
			filePath.mkdirs();
		}
		File dest = new File(desFileName);
		try {
			/*
			 * File fileOld = new File(path + dest); fileOld.delete();
			 */
			// 保存文件;
			file.transferTo(new File(path + dest));
			BufferedImage input = ImageIO.read(new File(path + dest));
			BufferedImage inputbig = new BufferedImage(50, 50, BufferedImage.TYPE_INT_BGR);
			Graphics2D g = (Graphics2D) inputbig.getGraphics();
			g.drawImage(input, 0, 0, 50, 50, null); // 画图
			g.dispose();
			input.flush();
			inputbig.flush();
			ImageIO.write(inputbig, "jpg", new File(path + dest)); // 将其保存在C:/imageSort/targetPIC/下
			return true;
		} catch (IOException e) {
			// LOGGER.error(e.toString(), e);
			return false;
		}
	}
}
